package com.probiz.estore.content.service.impl;

import java.util.Iterator;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;

import com.probiz.estore.common.model.content.Advertisement;
import com.probiz.estore.common.model.content.ProductAdvertisement;
import com.probiz.estore.content.dao.ProductAdvertisementDao;
import com.probiz.estore.core.service.impl.GenericManagerImpl;

public class ProductAdvertisementManagerImpl extends GenericManagerImpl<ProductAdvertisement> implements com.probiz.estore.content.service.ProductAdvertisementManager {

	ProductAdvertisementDao productAdvertisementDao=null;

	@Override
	protected void initManager() {
		this.dao=productAdvertisementDao;
		
	}

	@Override
	protected void preDelete(ProductAdvertisement entity) {
		
	}

	@Override
	protected void preSave(ProductAdvertisement entity) {
		
	}

	public void setProductAdvertisementDao(ProductAdvertisementDao productAdvertisementDao) {
		this.productAdvertisementDao = productAdvertisementDao;
	}

	public void saveProductAdvertisementsFromArrays(Advertisement advertisement, String[] categoryIds, String[] isSubIncludeds){
		Set<ProductAdvertisement> preRelations = advertisement.getProductAdvertisements();
		//删除
		Iterator iterator = preRelations.iterator();
		while(iterator.hasNext()){
			ProductAdvertisement relation = (ProductAdvertisement)iterator.next();
			if(null != categoryIds){
				if(!ArrayUtils.contains(categoryIds, relation.getCategoryId().toString())){
					this.delete(relation);
					iterator.remove();
				}
			}else{
				this.delete(relation);
				iterator.remove();
			}
		}
			
		//增加或修改
		if(null != categoryIds){
			for(int i=0; i<categoryIds.length; i++){
				Integer categoryId = Integer.valueOf(categoryIds[i]);
				Short isSubIncluded = Short.valueOf(isSubIncludeds[i]);
				ProductAdvertisement productAdvertisement=null;
				iterator = preRelations.iterator();
				while(iterator.hasNext()){
					ProductAdvertisement relation = (ProductAdvertisement)iterator.next();
					if(relation.getCategoryId().equals(categoryId)){
						productAdvertisement = relation;
					}
				}	
				if(null == productAdvertisement){
					productAdvertisement = new ProductAdvertisement();
					productAdvertisement.setAdvertisement(advertisement);
					productAdvertisement.setCategoryId(categoryId);
				}
				productAdvertisement.setIsSubIncluded(isSubIncluded);
				this.save(productAdvertisement);
			}
			
		}
	}

}
